using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Hospital;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.Infrastructure.Interface;
using B.S.NewMedical.Infrastructure;
using B.S.NewMedical.ErrorCode;
using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.ContentManagement.Hospital
{
    /// <summary>
    /// 新增医院命令处理器
    /// </summary>
    public class AddHospitalCommandHandler : IRequestHandler<AddHospitalCommand, ApiResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<HospitalModel> _hospitalRepository;
        private readonly IBaseRepository<HospitalDepartmentModel> _hospitalDepartmentRepository;
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly MyDbcontext _dbContext;
        private readonly ILogger<AddHospitalCommandHandler> _logger;

        public AddHospitalCommandHandler(
            IMapper mapper, 
            IBaseRepository<HospitalModel> hospitalRepository,
            IBaseRepository<HospitalDepartmentModel> hospitalDepartmentRepository,
            IBaseRepository<DepartmentModel> departmentRepository,
            MyDbcontext dbContext,
            ILogger<AddHospitalCommandHandler> logger)
        {
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
            _hospitalRepository = hospitalRepository ?? throw new ArgumentNullException(nameof(hospitalRepository));
            _hospitalDepartmentRepository = hospitalDepartmentRepository ?? throw new ArgumentNullException(nameof(hospitalDepartmentRepository));
            _departmentRepository = departmentRepository ?? throw new ArgumentNullException(nameof(departmentRepository));
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 处理新增医院命令
        /// </summary>
        /// <param name="request">新增医院命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>新增的医院ID</returns>
        public async Task<ApiResult<int>> Handle(AddHospitalCommand request, CancellationToken cancellationToken)
        {
            // 参数验证
            if (string.IsNullOrWhiteSpace(request.HospitalName))
            {
                return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "医院名称不能为空" };
            }

            try
            {
                // 开启事务
                using (var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken))
                {
                    try
                    {
                        _logger.LogInformation("开始创建医院：{HospitalName}", request.HospitalName);

                        // 验证科室ID是否存在
                        if (request.DepartmentIds != null && request.DepartmentIds.Any())
                        {
                            var existingDepartments = await _departmentRepository.GetAll()
                                .Where(d => request.DepartmentIds.Contains(d.Id) && !d.IsDeleted)
                                .Select(d => d.Id)
                                .ToListAsync(cancellationToken);

                            var invalidDepartmentIds = request.DepartmentIds.Except(existingDepartments).ToList();
                            if (invalidDepartmentIds.Any())
                            {
                                return new ApiResult<int> 
                                { 
                                    Code = ApiEnum.Fail, 
                                    Msg = $"科室ID不存在：{string.Join(", ", invalidDepartmentIds)}" 
                                };
                            }
                        }

                        // 创建医院实体
                        var hospitalEntity = _mapper.Map<HospitalModel>(request);
                        hospitalEntity.CreateTime = DateTime.Now;
                        hospitalEntity.CreatePeople = request.CreatePeople;
                        hospitalEntity.IsDeleted = false;

                        // 保存医院信息
                        await _hospitalRepository.CreateAsync(hospitalEntity);
                        _logger.LogInformation("医院创建成功，ID：{HospitalId}", hospitalEntity.Id);

                        // 创建医院科室关联
                        if (request.DepartmentIds != null && request.DepartmentIds.Any())
                        {
                            var hospitalDepartments = new List<HospitalDepartmentModel>();
                            foreach (var departmentId in request.DepartmentIds)
                            {
                                var hospitalDepartment = new HospitalDepartmentModel
                                {
                                    HospitalId = hospitalEntity.Id,
                                    DepartmentId = departmentId,
                                    IsDeleted = false
                                };
                                hospitalDepartments.Add(hospitalDepartment);
                            }

                            // 批量保存医院科室关联
                            foreach (var hospitalDepartment in hospitalDepartments)
                            {
                                await _hospitalDepartmentRepository.CreateAsync(hospitalDepartment);
                            }

                            _logger.LogInformation("医院科室关联创建成功，医院ID：{HospitalId}，关联科室数：{Count}", 
                                hospitalEntity.Id, hospitalDepartments.Count);
                        }

                        // 提交事务
                        await transaction.CommitAsync(cancellationToken);

                        return new ApiResult<int>
                        {
                            Code = ApiEnum.Success,
                            Msg = "医院创建成功",
                            Data = hospitalEntity.Id
                        };
                    }
                    catch (Exception ex)
                    {
                        // 回滚事务
                        await transaction.RollbackAsync(cancellationToken);
                        _logger.LogError(ex, "创建医院失败：{HospitalName}", request.HospitalName);
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建医院时发生异常：{HospitalName}", request.HospitalName);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = "创建医院失败：" + ex.Message
                };
            }
        }
    }
}